package com.net.xpay.core.service.impl;

import com.net.xpay.common.domain.notify.ChargeNotifyRecord;
import com.net.xpay.common.enums.notify.NotifyStatus;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.xpay.common.manager.notify.ChargeNotifyRecordManager;
import com.net.xpay.core.service.ChargeNotifyRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 86188
 */
@Slf4j
@Service
public class ChargeNotifyRecordServiceImpl implements ChargeNotifyRecordService {

    @Autowired
    private ChargeNotifyRecordManager chargeNotifyRecordManager;

    @Override
    public void initiateChargeNotify(Long id) {
        if (id == null){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        ChargeNotifyRecord chargeNotifyRecord = chargeNotifyRecordManager.getById(id);
        if (chargeNotifyRecord == null){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "回调记录不存在");
        }
        if (chargeNotifyRecord.getStatus().equals(NotifyStatus.INIT) || chargeNotifyRecord.getStatus().equals(NotifyStatus.OK)){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "回调记录状态异常");
        }
        if (chargeNotifyRecord.getStatus().equals(NotifyStatus.DEAD)){
            chargeNotifyRecord.setStatus(NotifyStatus.WAIT);
        }
        chargeNotifyRecord.setNotifyCount(0);
        chargeNotifyRecord.setNextNotifyTime(LocalDateTime.now());
        chargeNotifyRecordManager.update(chargeNotifyRecord);
    }
}
